package org.example.es.configuration;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.example.domain.User;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.stream.IntStream;

/**
 * @author Tang
 * @classname IndexApis
 * @description [  ]
 * @date 2023/4/22 16:53
 */
public class IndexApis {

    public static void main(String[] args) throws Exception{
        final RestHighLevelClient client = new EsConfiguration().restHighLevelClient();

        final IndexApis appMain = new IndexApis();
        appMain.createBatchIndex(client);

//        appMain.createIndex(client);
//        appMain.getIndex(client);
//        appMain.getExists(client);

        client.close();
    }

    public void createBatchIndex(RestHighLevelClient client) throws Exception{
        final BulkRequest request = new BulkRequest();
        LocalDate localDate = LocalDate.now();
        IntStream.range(0,1000)
                .forEach((id) -> {
                    final IndexRequest indexRequest = new IndexRequest("users");
                    final User user = new User();
                    user.setAge(id);
                    user.setName("tang" + id);
                    int num = -10 + new Random().nextInt(20);
                    user.setBirth(Date.from(localDate.plusDays(Long.parseLong(num+"")).atStartOfDay(ZoneId.systemDefault()).toInstant()));
                    String str = JSONObject.toJSONString(user);
                    indexRequest.id(String.valueOf(id)).source(str,XContentType.JSON);
                    indexRequest.opType(DocWriteRequest.OpType.CREATE);
                    request.add(indexRequest);
                });

        final BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);

        for (BulkItemResponse bulkItemResponse : bulkResponse) {
            DocWriteResponse itemResponse = bulkItemResponse.getResponse();
            switch (bulkItemResponse.getOpType()) {
                case INDEX:
                case CREATE:
                    IndexResponse indexResponse = (IndexResponse) itemResponse;
                    System.out.println(indexResponse);
                    break;
                case UPDATE:
                    UpdateResponse updateResponse = (UpdateResponse) itemResponse;
                    break;
                case DELETE:
                    DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
                default:
                    break;
            }
        }
    }

    public void createIndex(RestHighLevelClient client) throws Exception{
        IndexRequest request = new IndexRequest("users");
        request.id("2");
        final User user = new User();
        user.setAge(18);
        user.setName("tang");
        String str = JSONObject.toJSONString(user);
        request.source(str, XContentType.JSON);
        request.opType(DocWriteRequest.OpType.CREATE);
        final IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());

        if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
            System.out.println("CREATED");
        } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
            System.out.println("UPDATED");
        }
        ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                String reason = failure.reason();
                System.out.println(reason);
            }
        }
    }

    public void getIndex(RestHighLevelClient client) throws Exception{

        GetRequest request = new GetRequest("users","1");
//        request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);

        final GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response);

        if (response.isExists()) {
            Map<String, Object> sourceAsMap = response.getSourceAsMap();
            System.out.println("result = " + JSONObject.toJSONString(sourceAsMap));
        } else {
            System.out.println("not found!");
        }
    }

    public void getExists(RestHighLevelClient client) throws Exception{
        GetRequest request = new GetRequest("users","1");
        request.fetchSourceContext(new FetchSourceContext(false));
        final boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    public void getSourceRequest(RestHighLevelClient client) throws Exception{
        GetRequest request = new GetRequest("users","1");
        request.fetchSourceContext(new FetchSourceContext(false));
        final boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

}
